const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const Admin = require('../models/adminModel');
const { JWT_SECRET, JWT_EXPIRES_IN } = require('../config/jwt');

class AuthController {
    static async register(req, res) {
        try {
            const { username, email, password } = req.body;
            
           
            const existingUser = await User.findByEmail(email);
            if (existingUser) {
                return res.status(400).json({
                    success: false,
                    message: 'User already exists with this email'
                });
            }

            
            const userId = await User.create({ username, email, password });
            
           
            const token = jwt.sign(
                { userId, email, role: 'user' },
                JWT_SECRET,
                { expiresIn: JWT_EXPIRES_IN }
            );

            res.status(201).json({
                success: true,
                message: 'User registered successfully',
                token
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error registering user',
                error: error.message
            });
        }
    }

    static async login(req, res) {
        try {
            const { email, password } = req.body;

          
            const user = await User.findByEmail(email);
            if (!user) {
                return res.status(401).json({
                    success: false,
                    message: 'Invalid credentials'
                });
            }

            // Validate password
            const isValidPassword = await User.validatePassword(password, user.password);
            if (!isValidPassword) {
                return res.status(401).json({
                    success: false,
                    message: 'Invalid credentials'
                });
            }

            // Generate JWT token
            const token = jwt.sign(
                { userId: user.user_id, email: user.email, role: 'user' },
                JWT_SECRET,
                { expiresIn: JWT_EXPIRES_IN }
            );

            res.json({
                success: true,
                message: 'Login successful',
                token
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error during login',
                error: error.message
            });
        }
    }

    static async adminLogin(req, res) {
        try {
            const { email, password } = req.body;

            // Find admin
            const admin = await Admin.findByEmail(email);
            if (!admin) {
                return res.status(401).json({
                    success: false,
                    message: 'Invalid credentials'
                });
            }

            // Validate password
            const isValidPassword = await Admin.validatePassword(password, admin.password);
            if (!isValidPassword) {
                return res.status(401).json({
                    success: false,
                    message: 'Invalid credentials'
                });
            }

            // Generate JWT token
            const token = jwt.sign(
                { 
                    adminId: admin.admin_id, 
                    email: admin.email,
                    role: 'admin'
                },
                JWT_SECRET,
                { expiresIn: JWT_EXPIRES_IN }
            );

            res.json({
                success: true,
                message: 'Admin login successful',
                token
            });
        } catch (error) {
            res.status(500).json({
                success: false,
                message: 'Error during admin login',
                error: error.message
            });
        }
    }
}

module.exports = AuthController; 